package com.hbzhit.modules.oss.cloud;

import com.hbzhit.common.exception.RRException;
import com.hbzhit.common.utils.SpringContextUtils;
import com.hbzhit.modules.oss.config.CloudStorageConfig;
import com.hbzhit.modules.oss.config.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 七牛云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
@Slf4j
public class LocalStorageService extends CloudStorageService {
    private OssProperties ossProperties;

    public LocalStorageService(CloudStorageConfig config){
        this.config = config;
        //初始化
        init();
    }

    private void init(){
        ossProperties = SpringContextUtils.getBean("ossProperties", OssProperties.class);
    }

    @Override
    public String upload(byte[] data, String path) {
        File file = new File(ossProperties.getFileUploadConfig().getPath() + path);
        File filePath = file.getParentFile();
        log.info("文件的保存路径：" + path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            log.warn("目录不存在，创建目录:" + filePath);
            filePath.mkdirs();
        }

        //将文件保存到服务器指定位置
        try {
            FileCopyUtils.copy(data, file);
        } catch (IOException e) {
            throw new RRException("上传本地文件失败！", e);
        }
        //将文件在服务器的存储路径返回
        return path;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new RRException("上传文件失败", e);
        }
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getLocalPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getLocalPrefix(), suffix));
    }
}
